package net.wicp.tams.common.binlog.self.event;

import com.alibaba.fastjson.JSONArray;

import io.thekraken.grok.api.Match;
import io.thekraken.grok.api.exception.GrokException;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.GrokObj;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.binlog.self.bean.EventBean;
import net.wicp.tams.common.binlog.self.bean.Host;
import net.wicp.tams.common.binlog.self.sender.ISender;
import net.wicp.tams.common.thread.threadlocal.PerthreadManager;

@Slf4j
public class QueryEvent extends AbsEvent {

	private JSONArray statusVars;
	private String db;
	private String query;

	public QueryEvent(EventBean event) {
		super(event);
	}

	static {
		GrokObj gm = GrokObj.getInstance();
		gm.addPattern("db", "[A-Za-z0-9_.-:]+");
	}

	@Override
	public Result parseBody(ISender... senders) {
		super.logBuffer.forward(8);// assitRead.skip(8);
		int dbLength = super.logBuffer.getUint8();// ByteUtil.readIntL(assitRead.readBytes(1));
		super.logBuffer.forward(2);// assitRead.skip(2);
		int statusVarsLength = super.logBuffer.getInt16();// ByteUtil.readIntL(assitRead.readBytes(2));

		super.logBuffer.forward(statusVarsLength);

		// JSONObject updateVar = StatusVar.parseUpdatedDbNames(new
		// AssitRead(assitRead.readBytes(statusVarsLength)));
		db = super.logBuffer.getFixString(dbLength);// ByteUtil.readString(assitRead.readBytes(dbLength));
		super.logBuffer.forward(1);
		query = super.logBuffer.getFixString(super.logBuffer.remaining());// ByteUtil.readString(assitRead.readRest());
		// skip(EventType.QUERY_EVENT.getPostHeaderLength());// 不解析posthead
		if (statusVarsLength > 0 && query.startsWith("ALTER")) {// 已经修改了表,现只支持修改一张表
			int index = query.indexOf("\r\n");
			String firStr = index < 0 ? query : query.substring(0, index);
			try {
				Match mt = GrokObj.getInstance().match("ALTER TABLE `%{tb}`", firStr);
				String tb = (String) mt.toMap().get("tb");
				if (StringUtil.isNotNull(tb)) {
					Host host = (Host) PerthreadManager.getInstance().createValue("zorro-host").get();
					host.delCols(db, tb);
				}
			} catch (GrokException e) {
				log.error("解析表信息出错", e);
			}
		}
		return Result.getSuc();
	}

	public JSONArray getStatusVars() {
		return statusVars;
	}

	public String getDb() {
		return db;
	}

	public String getQuery() {
		return query;
	}

}
